package org.wso2.carbon.registry.lifecycle.accenture.sample;


import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.wso2.carbon.governance.api.util.GovernanceConstants;
import org.wso2.carbon.registry.core.Resource;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.jdbc.handlers.Handler;
import org.wso2.carbon.registry.core.jdbc.handlers.RequestContext;

import javax.xml.namespace.QName;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.io.StringReader;
import java.util.UUID;


/*
<handler class="org.wso2.carbon.registry.lifecycle.accenture.sample.ServiceCreationHandler">
        <filter class="org.wso2.carbon.registry.core.jdbc.handlers.filters.MediaTypeMatcher">
            <property name="mediaType">application/vnd.wso2-request+xml</property>
        </filter>
        <property name="artifactPath">servicedesigns</property>
        <property name="targetServiceMediaType">application/vnd.wso2-servicedesign+xml</property>
</handler>
 */

/**
 * This class used to auto generate when service request happen
 */
public class ServiceCreationHandler extends Handler {

    private final String NEW_REQUEST_MEDIA_TYPE = "application/vnd.wso2-request+xml";
    private String email;
    private String name;
    private String version;
    private String nameSpace;
    private String lcName = "None";
    OMElement lifeCycleNameOMOmElement;

    public String getTargetServiceMediaType() {
        return targetServiceMediaType;
    }

    public void setTargetServiceMediaType(String targetServiceMediaType) {
        this.targetServiceMediaType = targetServiceMediaType;
    }

    public String getArtifactPath() {
        return artifactPath;
    }

    public void setArtifactPath(String artifactPath) {
        this.artifactPath = artifactPath;
    }

    private String targetServiceMediaType;
    private String artifactPath;

    @Override
    public void put(RequestContext requestContext) throws RegistryException {

        Resource resource = requestContext.getResource();
        String mediaType = resource.getMediaType();
        String lcPropertyName = resource.getProperty("registry.LC.name");
        //When we are adding a LC for the request artifact this handler going to hit
        //To prevent that lcPropertyName==null condition checked.
        if (!(mediaType.equals(NEW_REQUEST_MEDIA_TYPE)) || lcPropertyName!=null) {
            return;
        }
        String requestServiceString = resource.getContent().toString();
        XMLStreamReader reader = null;
        try {
            reader = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(requestServiceString));
        } catch (XMLStreamException e) {
            e.printStackTrace();
        }
        StAXOMBuilder builder = new StAXOMBuilder(reader);
        OMElement serviceElement = builder.getDocumentElement();
        String xmlNs = serviceElement.getNamespace().getName();
        OMElement overviewOmElement = serviceElement.getFirstElement();
        OMElement serviceLifecycleOmElement = serviceElement.getFirstChildWithName(new QName(xmlNs, "serviceLifecycle"));
        if (serviceLifecycleOmElement != null) {
            lifeCycleNameOMOmElement = serviceLifecycleOmElement.getFirstChildWithName(new QName(xmlNs, "lifecycleName"));
        }
        OMElement emailOmElement = overviewOmElement.getFirstChildWithName(new QName(xmlNs, "email"));
        OMElement nameOmElement = overviewOmElement.getFirstChildWithName(new QName(xmlNs, "name"));
        OMElement versionOmElement = overviewOmElement.getFirstChildWithName(new QName(xmlNs, "version"));
        OMElement nameSpaceOmElement = overviewOmElement.getFirstChildWithName(new QName(xmlNs, "namespace"));
        if (emailOmElement != null) {
            email = emailOmElement.getText();
        }
        if (nameOmElement != null) {
            name = nameOmElement.getText();
        }
        if (versionOmElement != null) {
            version = versionOmElement.getText();
        }
        if (nameSpaceOmElement != null) {
            nameSpace = nameSpaceOmElement.getText();
        }
        if (lifeCycleNameOMOmElement != null) {
            lcName = lifeCycleNameOMOmElement.getText();
        }
        //Creating a new service with added details from new service request
        String serviceDefn =
                "<metadata xmlns=\"http://www.wso2.org/governance/metadata\">" +
                        "<overview>" +
                            "<email>" + email + "</email>" +
                            "<name>" + name + "</name>" +
                            "<version>" + version + "</version>" +
                            "<namespace>" + nameSpace + "</namespace>" +
                            "</overview>" +
                        "<serviceLifecycle>" +
                            "<lifecycleName>" + lcName + "</lifecycleName>" +
                        "</serviceLifecycle>" +
                "</metadata>";
        // Here we are creating a new configurable gov artifact.
        byte[] rxtBytes = serviceDefn.getBytes();
        Resource newRxtResource = requestContext.getRegistry().newResource();
        newRxtResource.setContent(rxtBytes);
        newRxtResource.setMediaType(targetServiceMediaType);
        newRxtResource.setProperty(GovernanceConstants.ARTIFACT_ID_PROP_KEY, UUID.randomUUID().toString());
        String gov_prefix = "/_system/governance/";
        String newResourcePath = gov_prefix + artifactPath + "/" + name + "/" + version;
        requestContext.getRegistry().put(newResourcePath, newRxtResource);

    }

}
